package cn.xiuxius.embedded.toolwindow;

public class SerialUtils {
    public static String bytesToHex(byte[] bytes, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(String.format("%02X ", bytes[i]));
        }
        return sb.toString().trim();
    }

    public static byte[] hexStringToByteArray(String hex) {
        hex = hex.replaceAll("[^0-9A-Fa-f]", "");
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException("Hex字符串长度必须为偶数");
        }
        byte[] data = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length(); i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }

    public static String formatHexString(String hex, int groupSize) {
        String clean = hex.replaceAll("[^0-9A-Fa-f]", "");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < clean.length(); i += groupSize * 2) {
            for (int j = 0; j < groupSize * 2 && i + j < clean.length(); j += 2) {
                sb.append(clean, i + j, i + j + 2).append(" ");
            }
            sb.append("\n");
        }
        return sb.toString().trim();
    }
}
